package com.cavy.platform.server.validator;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.CavyConfig;
import com.cavy.platform.server.util.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 验证图片不能为空
 */
public class ImageNotNullValidator implements ConstraintValidator<ImageNotNull, MultipartFile> {
    private CavyConfig config;

    @Override
    public void initialize(ImageNotNull notRepeatPluginName) {
        config = BeansProvider.getBean(CavyConfig.class);
    }

    @Override
    public boolean isValid(MultipartFile dto, ConstraintValidatorContext context) {
        if (dto != null && !dto.isEmpty()) {
            String fileExt = FileUtils.getFileExt(dto.getOriginalFilename());
            if (config.getPlugin().getLogoExt().contains(fileExt)) {
                return true;
            } else {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("不支持的图片格式").addConstraintViolation();
                return false;
            }
        }
        return false;
    }
}
